package com.zhao.comm.log;

import com.alibaba.fastjson.JSON;
import com.zhao.Util.HttpContextUtil;
import com.zhao.Util.IPUtil;
import com.zhao.Util.ShiroUtils;
import com.zhao.pojo.Log;
import com.zhao.pojo.User;
import com.zhao.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
 
/**
 * 系统日志：切面处理类
 */
@Aspect
@Component
public class SysLogAspect {
 
    @Autowired
    private LogService logService;
 
    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( com.zhao.comm.log.MyLog)")
    public void logPoinCut() {
    }
 
    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        System.out.println("切面。。。。。");
        //保存日志
        Log log = new Log();
 
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
 
        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            String value = myLog.value();
            log.setOperation(value);//保存获取的操作
        }
 
        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        log.setMethod(className + "." + methodName);
 
        //请求的参数
        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
       // System.out.println(Arrays.toString(args));
        //String params = JSON.toJSONString(args);
        log.setParams(Arrays.toString(args));
 
        /*log.setCreateDate(new Date());*/
        //获取用户名
        String userAccount = ((User) ShiroUtils.getSubject().getPrincipal()).getUserAccount();
        if (userAccount==null){
            userAccount="游客";
        }
        log.setUsername(userAccount);
        //获取用户ip地址
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        log.setIp(IPUtil.getIpAddr(request));
 
        //调用service保存log实体类到数据库
        logService.save(log);
    }
 
}